const { User } = require('../model')
const jwt = require('../util/jwt')
const { jwtSecret } = require('../config/config.default')

exports.login = async (req, res, next) => {
    try {
        // const user = req.body.toJSON()
        // res.status(200).json({
        //     user
        // })
        const user = req.body
        const token = await jwt.sign({
            userId: user._id
        }, jwtSecret, {
            expiresIn: 60 * 60 * 24
        })
        delete user.password
        res.status(200).json({
            ...user,
            token
        })
    } catch (error) {
        next(error)
    }
}
exports.register = async (req, res, next) => {
    try {
        console.log('注册', req.body)
        let user = new User(req.body)
        await user.save()

        user = user.toJSON()

        delete user.password

        res.status(201).json({
            user
        })
    } catch (error) {
        next(error)
    }
}
exports.getCurrentUser = async (req, res, next) => {
    console.log('获取用户信息')
    try {
        delete req.body.password

        res.status(200).json({
          user: req.body
        })
      } catch (err) {
        next(err)
      }
}